package com.hua.demo03.service.impl;

import com.hua.demo03.commons.JwtUtil;
import com.hua.demo03.commons.RedisCache;
import com.hua.demo03.pojo.MyUserDetails;
import com.hua.demo03.pojo.User;
import com.hua.demo03.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseEntity<Map<String, String>> login(User user) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authentication = authenticationManager.authenticate(token);
        if(Objects.isNull(authentication)){
            return (ResponseEntity<Map<String, String>>) ResponseEntity.badRequest();
        }
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        String userId = String.valueOf(userDetails.getUser().getId());
        String tokenU = JwtUtil.createJWT(userId);

        redisCache.setCacheObject("login:"+userId, tokenU,30, TimeUnit.MINUTES);
        Map<String, String> map = new HashMap<>();
        map.put("token", tokenU);
        map.put("userId", userId);
        return ResponseEntity.ok(map);
    }
}
